package com.yvtian.utils;

import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.xssf.usermodel.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

public class ExcelUtil {
    public static final String[] ROLE_COLUMN = {"id", "角色名称", "角色描述", "创建时间", "更新时间", "是否启用"};

    /**
     * 用户信息导出类
     *
     * @param response   响应
     * @param columnList 每列的标题名
     * @param dataList   导出的数据
     */
    public static void uploadExcelAboutUser(HttpServletResponse response, String sheetName, List<String> columnList, List<List<String>> dataList) {
        //声明输出流
//        OutputStream os = null;
        //设置响应头
//        setResponseHeader(response,fileName);
        // 第一步，创建一个webbook，对应一个Excel文件
        XSSFWorkbook wb = new XSSFWorkbook();//Excel2007
//        HSSFWorkbook wb = new HSSFWorkbook();//Excel2003以前（包括2003）
        // 第二步，在webbook中添加一个sheet,对应Excel文件中的sheet
        XSSFSheet sheet = wb.createSheet(sheetName);
//        HSSFSheet sheet = wb.createSheet(sheetName);
        // 第三步，在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short
//        HSSFRow row = sheet.createRow(0);
        XSSFRow row = sheet.createRow(0);
        // 第四步，创建单元格，并设置值表头 设置表头居中
//        HSSFCellStyle style = wb.createCellStyle();
        XSSFCellStyle style = wb.createCellStyle();
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式


        //第五步，创建标题
        for (int i = 0; i < columnList.size(); i++) {
//            HSSFCell cell = row.createCell(i);
            XSSFCell cell = row.createCell(i);
            cell.setCellValue(columnList.get(i));
        }

        //第六步，写入实体数据，遍历创建内容
        for (int i = 0; i < dataList.size(); i++) {//总共多少行
            List<String> list = dataList.get(i);
            row = sheet.createRow(i + 1);//第几行
            //将内容按顺序赋给对应的列对象
            for (int i1 = 0; i1 < list.size(); i1++) {
                row.createCell(i1).setCellValue(list.get(i1));//每行塞什么数据
            }
        }

        //第六步，下载excel表格
        OutputStream out = null;
        try {
            out = response.getOutputStream();
            String fileName = UUID.randomUUID().toString() + ".xls";// 文件名
            setResponseHeader(response, fileName);
            wb.write(out);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static List<List<String>> readExcel(InputStream inputStream) {
        List<List<String>> lists = new ArrayList<>();
        try {
            XSSFWorkbook sheets = new XSSFWorkbook(inputStream);
            for (int i = 0; i < sheets.getNumberOfSheets(); i++) {
                XSSFSheet sheet = sheets.getSheetAt(i);
                //第一列为列名
//                XSSFRow firstRow = sheet.getRow(0);
//                List<String> list = new ArrayList<>();
//                for (int j = 0; j < ((int) firstRow.getLastCellNum()); j++) {
//                    list.add(firstRow.getCell(j).getStringCellValue())
//                }
//                lists.add(list);
                //开始获取数据
                for (int j = 1; j <= sheet.getLastRowNum(); j++) {
                    //获取每一行
                    XSSFRow row = sheet.getRow(j);
                    List<String> list = new ArrayList<>();
                    for (int k = 0; k < ((int) row.getLastCellNum()); k++) {
                        //获取每一列
                        XSSFCell cell = row.getCell(k);
                        //取值
                        String value = cell.getStringCellValue();
                        list.add(value);
                    }
                    lists.add(list);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return lists;
    }

    /*
        设置浏览器下载响应头
     */
    private static void setResponseHeader(HttpServletResponse response, String fileName) {
        try {
            try {
                fileName = new String(fileName.getBytes(), "ISO8859-1");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            response.setContentType("application/octet-stream;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            response.addHeader("Pargam", "no-cache");
            response.addHeader("Cache-Control", "no-cache");
            //后端代码响应头部需要设置Access-Control-Expose-Headers头部信息，把你需要获取的头部属性字段设置在这个值里面前端响应部分就可以获取，否则不可无法获取（多个用逗号分割），如下设置前端可以获取文件名字，
            response.addHeader("Access-Control-Expose-Headers", "Content-Disposition");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}
